import { MessageBody, SubscribeMessage, WebSocketGateway, WebSocketServer } from '@nestjs/websockets';
import { ChatService } from './chat.service';
import { Server, Socket } from 'socket.io';
import { Inject } from '@nestjs/common';
import { ChatHistoryService } from '../chat-history/chat-history.service';
import { UserId } from '@/common/decorator/param.decorator';
import { UserService } from '../user/user.service';
interface JoinRoomPayload {
    chatroomId: number
    userId: number
}

interface SendMessagePayload {
    sendUserId: number;
    chatroomId: number;
    message: {
        type: 'text' | 'image',
        content: string
    }
}
@WebSocketGateway({ cors: { origin: '*' } })
export class ChatGateway {
    @WebSocketServer() server: Server;

    @Inject()
    private readonly chatService: ChatService;

    @Inject()
    private readonly chatHistoryService: ChatHistoryService;

    @Inject()
    private readonly userService: UserService;

    @SubscribeMessage('joinRoom')
    joinRoom(client: Socket, payload: JoinRoomPayload): void {
        console.log(client.request, '用户id');

        const { chatroomId, userId } = payload;
        const roomName = chatroomId.toString()
        client.join(roomName);
        this.server.to(roomName).emit('message', {
            type: 'joinRoom',
            userId: payload.userId
        })
    }
    @SubscribeMessage('sendMessage')
    async sendMessage(@MessageBody() payload: SendMessagePayload) {
        const roomName = payload.chatroomId.toString()
        const history = await this.chatHistoryService.add(payload.chatroomId, {
            senderId: payload.sendUserId,
            content: payload.message.content,
            type: payload.message.type === 'image' ? 1 : 0,
            chatroomId: payload.chatroomId
        })
        const sender = await this.userService.findUserById(history.senderId)
        this.server.to(roomName).emit('message', {
            type: 'sendMessage',
            userId: payload.sendUserId,
            message: {
                ...history,
                sender
            }
        })
    }

}
